﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Warehouse.Web.AppCode
{
    public class BasePage : System.Web.UI.Page
    {
        public override void ProcessRequest(HttpContext context)
        {
            if (context.Request.Headers["Accept"].IndexOf("application/json") > -1)
            {
                try
                {
                    ProcessAjaxRequest(context);
                }
                catch (Exception ex)
                {
                    WebUtil.WriteJsonError(context, ex.Message);
                }
            }
            else
            {
                base.ProcessRequest(context);
            }
        }

        protected override void OnInit(EventArgs e)
        {

            bool result = Authority.Validate(this.Request.Url.AbsolutePath, "View", (DataAccess.PermissionInUser[])Session["UserPermission"]);

            if (!result)
            {
                if (this.User.Identity.IsAuthenticated)
                {
                    this.Response.Write("对不起，你没有权限查看该页面！");
                    this.Response.Flush();
                    this.Response.End();
                }
                else if (this.Master is Master.SiteContent)
                {
                    this.Response.Write("<script type='text/javascrpit'>(window.parent || window).location='" + this.ResolveUrl("~/Login.aspx") + "';</script>");
                    this.Response.Flush();
                    this.Response.End();
                }
                else
                {
                    this.Response.Redirect("~/Login.aspx");
                }
            }
            else
            {
                base.OnInit(e);
            }
        }

        protected virtual bool CheckAuthority(HttpContext context, string action)
        {
            return Authority.Validate(context.Request.Url.AbsolutePath, action, (DataAccess.PermissionInUser[])Session["UserPermission"]);
        }

        #region Process Ajax

        protected virtual void ProcessAjaxRequest(HttpContext context)
        {
            string action = context.Request.QueryString["action"];
            if (action == null)
            {
                action = context.Request.Form["action"];
            }

            bool result = CheckAuthority(context, action);// Authority.Validate(context.Request.Url.AbsolutePath, action, (DataAccess.PermissionInUser[])Session["UserPermission"]);

            if (!result)
            {
                if (context.User.Identity.IsAuthenticated)
                {
                    WebUtil.WriteJsonError(context, "对不起，你没有权限进行该操作！");
                }
                else
                {
                    WebUtil.WriteJson(context, new JsonResponse()
                    {
                        Code = JsonResponseCode.UNAUTHORIZED
                    });
                }
            }
            else
            {
                ProcessAjaxRequest(context, action);
            }
        }

        protected virtual void ProcessAjaxRequest(HttpContext context, string action)
        {
            WebUtil.WriteJsonError(context, "Not Implemented Ajax Request. Action: " + action);
        }

        #endregion

        #region RegisterClientScriptBlcok

        protected void RegisterClientScriptContent(string id, string scriptcontent)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), Guid.NewGuid().ToString("N"), "<script id=\"" + id + "\" type=\"text/javascript\">" + scriptcontent + "</script>");
        }

        protected void RegisterClientScript(string key, string scriptcontent, bool endresponse)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), key, "<script type=\"text/javascript\">" + scriptcontent + "</script>");
            if (endresponse)
            {
                Response.End();
            }
        }
        protected void RegisterClientScript(string key, string scriptcontent)
        {
            RegisterClientScript(key, scriptcontent, false);
        }

        protected void RegisterClientMessage(string msg, bool refreshOpener, bool closeWindow)
        {
            string script = "";
            if (!string.IsNullOrEmpty(msg))
            {
                script += "alert('" + msg.Replace("\r", "\\r").Replace("\n", "\\n").Replace("'", "\\'") + "');";
            }
            if (refreshOpener)
            {
                script += "if(window.opener){window.opener.location.reload();}";
            }
            if (closeWindow)
            {
                script += "window.close();";
            }
            RegisterClientScript("error", script, false);
        }

        protected void RegisterClientMessage(string msg)
        {
            RegisterClientMessage(msg, false, false);
        }



        #endregion

        #region CustomPrincipal

        public CustomIdentity UserInfo
        {
            get { return this.User.Identity as CustomIdentity; }
        }

        #endregion
    }
}
